# -*- coding: utf-8 -*-
import platform
import random
import threading
import time
from matplotlib.pylab import mpl
import serial
import device_model as deviceModel
from data_processor.roles.jy901s_dataProcessor import JY901SDataProcessor
from protocol_resolver.roles.wit_protocol_resolver import WitProtocolResolver
import UI
import graph
import jy901s_read
import tkinter as tk

mpl.rcParams['font.sans-serif'] = ['SimHei']  # 中文显示
mpl.rcParams['axes.unicode_minus'] = False  # 负号显示

global win, graphLabel

def updateLabel(label, data):
    pass

def updateWindow():
    global win, graphLabel
    #print('更新')
    graphLabel.updateMeltGraph()
    win.after(100, updateWindow)  # 1000ms更新画布

def updateLabelData(label, data):
    #print(data)
    label.config(text=f'x: {data[1]:.2f} y: {data[2]:.2f} z: {data[3]:.2f}')


def external_data_source(data_queue, data_queue2, reader):
    while True:
        #print(reader.read_acc())
        data_queue2.put(reader.read_acc())
        data = reader.read()
        #print(data)
        if len(data) > 1:
            data_queue.put(data)

ser = serial.Serial('COM8', 9600, timeout=1)
if __name__ == '__main__':
    # 窗口初始化
    win = tk.Tk()
    ui = UI.UIClass(win)
    ui.initWindow('test', '1000x500')

    # 设备初始化
    device = deviceModel.DeviceModel(
        "JY901s",
        WitProtocolResolver(),
        JY901SDataProcessor(),
        "51_0"
    )
    system = platform.system()
    if system == "Windows":
        device.serialConfig.portName = 'COM8'
    elif system == "Linux":
        device.serialConfig.portName = '/dev/ttyUSB0'
    else:
        print('未知设备')
        exit(0)

    device.serialConfig.baud = 9600  # 设置波特率  Set baud rate
    device.openDevice()  # 打开串口   Open serial port
    device.dataProcessor.onVarChanged.append(onUpdate)  # 数据更新事件 Data update event
    # 创建标签
    ui.addLabel('加速度', 'gray', ('Arial', 12), 10, 1, 3, updateLabel, 10, 10)
    ui.addLabel('角速度', 'gray', ('Arial', 12), 10, 1, 4, updateLabel, 10, 50)
    ui.addLabel('角度', 'gray', ('Arial', 12), 10, 1, 5, updateLabel, 10, 90)
    ui.addLabel('x: 0  y: 0  z: 0', 'gray', ('Arial', 12), 40, 1, 0, updateLabelData, 150, 10)
    ui.addLabel('x: 0  y: 0  z: 0', 'gray', ('Arial', 12), 40, 1, 1, updateLabelData, 150, 50)
    ui.addLabel('x: 0  y: 0  z: 0', 'gray', ('Arial', 12), 40, 1, 2, updateLabelData, 150, 90)

    # 创建图表
    graphFrame = tk.Frame(win, height=20, width=50)  # 创建图表控件
    graphFrame.place(x=10, y=150)

    graphLabel = graph.Graph(graphFrame, 5, 9)


    # 启动外部数据线程
    data_thread = threading.Thread(target=external_data_source, args=(ui.data_queue, graphLabel.data_queue, reader))
    data_thread.daemon = True
    data_thread.start()


    updateWindow()

    ui.loop()
    device.closeDevice()